package com.example.chatroom.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.chatroom.domain.UserInfo;
import com.example.chatroom.dto.SimpleUserRole;
import com.example.chatroom.repository.UserInfoRepository;
import com.example.chatroom.service.UserInfoService;
import com.example.chatroom.socket.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


@Service
public class UserInfoServiceImpl implements UserInfoService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private UserInfoRepository userInfoRepository;

    public UserInfoServiceImpl(UserInfoRepository userInfoRepository){
        this.userInfoRepository = userInfoRepository;
    }

    @Override
    public Boolean isExistUserName(String username) {
        return findByUserName(username) != null;
    }

    @Override
    public String register(String username, String password, String repassword) {
        if (username.isEmpty()) {
            return "用户名不能为空";
        }
        if (!isExistUserName(username)) {
          if (password.length() < 6 || password.length() > 16) {
              return "密码长度必须为6-16位";
          }
          if (password.equals(repassword)){
              UserInfo userInfo = new UserInfo();
              userInfo.setUsername(username);
              userInfo.setPassword(password);
              userInfo.setNickname(username);
              userInfo.setRole("普通用户");
              userInfoRepository.save(userInfo);
              return "注册成功";
          }
          return "两次密码输入不一致";
        }
        return "用户名已经存在";
    }

    @Override
    public Boolean login(String username, String password, HttpServletRequest request) {
        if (username.isEmpty()) {
            return false;
        }
        UserInfo userInfo = userInfoRepository.findByUsernameAndPassword(username, password);
        if (userInfo != null) {
            // TODO: 2018/12/17 其他操作待续
            request.getSession().setAttribute("userId", userInfo.getId());
            request.getSession().setAttribute("username", username);
            request.getSession().setAttribute("nickname", userInfo.getNickname());
            request.getSession().setAttribute("role", userInfo.getRole());
            return true;
        }
        return false;
    }

    @Override
    public void logout(HttpServletRequest request) {
        request.getSession().removeAttribute("nickname");
        request.getSession().removeAttribute("username");
        request.getSession().removeAttribute("userId");
        request.getSession().removeAttribute("role");
    }

    @Override
    public String forbidden(String nickname, HttpServletRequest httpServletRequest) {
        JSONObject jsonObject = new JSONObject();
        if (!"管理员".equals(httpServletRequest.getSession().getAttribute("role"))) {
            logger.info(httpServletRequest.getSession().getAttribute("role").toString());
            jsonObject.put("0","权限不足");
            return jsonObject.toJSONString();
        }
        UserInfo userInfo = userInfoRepository.findByNickname(nickname);
        if (userInfo != null) {
            userInfo.setState(!userInfo.getState());
            userInfoRepository.save(userInfo);
            Map<String,Object> map = new HashMap<>(16);
            map.put("messageType", 4);
            map.put("state",userInfo.getState());
            map.put("fromUsername", nickname);
            map.put("role", userInfo.getRole());
            WebSocket.sendMessageToAll(JSON.toJSONString(map), "管理员");
            jsonObject.put("state", userInfo.getState());
            return jsonObject.toJSONString();
        }
        jsonObject.put("0","没有此用户");
        return jsonObject.toJSONString();
    }

    @Override
    public String updateNickname(String nickname, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        if (nickname.isEmpty()) {
            jsonObject.put("code","0");
            jsonObject.put("msg","昵称不能为空");
            return jsonObject.toJSONString();
        }
        if (userInfoRepository.existsByNickname(nickname)) {
            jsonObject.put("code","0");
            jsonObject.put("msg","昵称已经存在");
            return jsonObject.toJSONString();
        }
        UserInfo userInfo = userInfoRepository.getOne((Long) request.getSession().getAttribute("userId"));
        userInfo.setNickname(nickname);
        userInfoRepository.save(userInfo);
        request.getSession().setAttribute("nickname", nickname);
        jsonObject.put("code","1");
        jsonObject.put("msg",nickname);
        return jsonObject.toJSONString();
    }

    @Override
    public String updatePassword(String oldPassword, String password, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        UserInfo userInfo = userInfoRepository.findByUsernameAndPassword(
                request.getSession().getAttribute("username").toString(),
                oldPassword);
        if (userInfo!=null) {
            if (password.length() < 6 || password.length() > 16) {
                jsonObject.put("code", "0");
                jsonObject.put("msg", "密码长度必须为6-16位");
                return jsonObject.toJSONString();
            }
            userInfo.setPassword(password);
            userInfoRepository.save(userInfo);
            jsonObject.put("code","1");
            jsonObject.put("msg","密码修改成功,请重新登录");
            request.getSession().removeAttribute("nickname");
            request.getSession().removeAttribute("userId");
            return jsonObject.toJSONString();
        }
        jsonObject.put("code","0");
        jsonObject.put("msg","原密码错误");
        return jsonObject.toJSONString();
    }

    @Override
    public Long getIdByNickname(String nickname) {
        return userInfoRepository.getIdByNickname(nickname);
    }

    @Override
    public String getNicknameById(Long id) {
        return userInfoRepository.getNicknameById(id);
    }

    @Override
    public SimpleUserRole getUserState(String nickname) {
        return userInfoRepository.getUserStateAndRoleByNickname(nickname);
    }

    private UserInfo findByUserName(String username) {
        return userInfoRepository.findByUsername(username);
    }
}
